package com.example.com.baruffini_mele.booking4u;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
/** The class GEvent is the abstraction of a Google Calendar event. 
*
* @author Carmen C. Baruffini
* @author G. Mele
* @version 1.0  Jan 5, 2013.
* 
*/
public class GEvent {
	/** Holds the Starting time of the event, expressed as HH:mm */
	private String startTime;
	/** Holds the Ending time of the event, expressed as HH:mm */
	private String endTime;
	/** Holds the Title of the event, expressed as a string */
	private String title;
	/** Holds the Day of the week, expressed as a string */
	private String day;
	/** Holds the Date of the event, expressed as a dd/MM/yyyy */
	private String eventDate;
	/** Holds the Calendar identifier */
	private String idCalendar;


	private static final String TAG = "GEvent";	
	/**
	 * @return the idCalendar
	 */
	public String getIdCalendar() {
		return idCalendar;
	}

	/**
	 * @param idCalendar the idCalendar to set
	 */
	public void setIdCalendar(String idCalendar) {
		this.idCalendar = idCalendar;
	}
	
	 /**
	* Empty constructor for GEvent
	*/
	public GEvent() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	 /**
	 * Default constructor for GEvent
	 * Sets properties: day of week, event Date, starting time, ending time, event title.
	 */
	public GEvent(String day,String eventDate, String startTime, String endTime, String title) {
		super();
		this.day = day;
		this.startTime = startTime;
		this.endTime = endTime;
		this.title = title;
		this.eventDate = eventDate;
	}
	
	
	/**
	 * @return the day
	 */
	public String getDay() {
		return day;
	}
	/**
	 * @param day the day to set
	 */
	public void setDay(String day) {
		this.day = day;
	}
	/**
	 * @return the startTime
	 */
	public String getStartTime() {
		return startTime;
	}
	/**
	 * @param startTime the startTime to set
	 */
	public void setStartTime(String startTime) {
		this.startTime = startTime;
	}
	/**
	 * @return the endTime
	 */
	public String getEndTime() {
		return endTime;
	}
	/**
	 * @param endTime the endTime to set
	 */
	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}
	/**
	 * @return the title
	 */
	public String getTitle() {
		return title;
	}
	/**
	 * @param title the title to set
	 */
	public void setTitle(String title) {
		this.title = title;
	}
	/**
	 * @return the eventDate
	 */
	public String getEventDate() {
		return eventDate;
	}
	/**
	 * @param eventDate the eventDate to set
	 */
	public void setEventDate(String eventDate) {
		this.eventDate = eventDate;
	}
	
	

	
	
	/**
	 * Returns the list of events of a calendar identified by idCalendar, 
	 * whose date is between two dates.
	 * This method creates HttpClient and HttpPost objects to execute a POST request, sets POST data
	 * executes the POST request, doing marshalling and unmarshalling by using JSON serialization format
	 * 
	 * @param idCalendar identifier of the calendar 
	 * @param firstDay date representing the left bound of time interval
	 * @param lastDay date representing the left bound of time interval
	 * @return eventList: the events list
	 */
	public  ArrayList postCalendarEvents(String idCalendar, String firstDay, String lastDay) {

		String result = ""; //result obtained from remote query   
		String eventTitle = "";
		String startTime = "";
		String endTime = "";
		String dayOfWeek = "";
		String eventDate = "";
		
		String urlString = "http://143.225.162.99/~carmen/dieti/ws/view_calendar.php";
		ArrayList<GEvent> eventList = new ArrayList<GEvent>();

		
//http post
		  		
		try{
			
		//Create  HttpClient and HttpPost objects to execute the POST request
		HttpClient httpclient = new DefaultHttpClient();
		
		HttpPost httppost = new HttpPost(urlString);
		//Set POST data
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("id_cal",idCalendar));
		nameValuePairs.add(new BasicNameValuePair("first_day",firstDay));
		nameValuePairs.add(new BasicNameValuePair("last_day",lastDay));
		httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		//Execute the POST request
		HttpResponse response = httpclient.execute(httppost);
		HttpEntity entity = response.getEntity();
		InputStream is = entity.getContent();
		
		
		
		//convert response to string
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null) {
		     sb.append(line + "\n");
		}
		is.close();
		
		result=sb.toString();

		 } 
		catch(Exception e){
			e.printStackTrace();
		}

		//parse json data
		try{
		JSONArray jArray = new JSONArray(result);
		for(int i=0;i<jArray.length();i++){
		        JSONObject json_data = jArray.getJSONObject(i);
		        dayOfWeek = json_data.getString("day_of_week");
		        eventDate = json_data.getString("event_date");
		        eventTitle = json_data.getString("event_title");
		        startTime = json_data.getString("start_time");
		        endTime = json_data.getString("end_time");
		        
	    
		        eventList.add(new GEvent(dayOfWeek, eventDate, startTime, endTime, eventTitle));
		        
		}
		
		}catch(JSONException e){
		Log.e(TAG, "Error parsing data "+e.toString());
		}
		return eventList;
    
    }
	

	/**
	 * Insert an object GEvent into a remote Google calendar identified by idCalendar. 
	 * This method creates HttpClient and HttpPost objects to execute a POST request, sets POST data
	 * executes the POST request, doing marshalling and unmarshalling by using JSON serialization format
	 * 
	 * 
	 * @return idEvent: the id of the event just inserted
	 */	
	public String postNewEvent() {
		String idEvent = "";
     	String urlString = "http://143.225.162.99/~carmen/dieti/ws/new_event.php";
        String row = "";
       
       //http post
		  		
		try{
			
		//Create  HttpClient and HttpPost objects to execute the POST request
		HttpClient httpclient = new DefaultHttpClient();
		
		HttpPost httppost = new HttpPost(urlString);
		//Set POST data
		
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("id_cal",idCalendar));
		nameValuePairs.add(new BasicNameValuePair("event_day",eventDate));
		nameValuePairs.add(new BasicNameValuePair("starting_time",startTime));
		nameValuePairs.add(new BasicNameValuePair("ending_time",endTime));
		nameValuePairs.add(new BasicNameValuePair("title",title));
		httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		//Execute the POST request
		HttpResponse response = httpclient.execute(httppost);
		HttpEntity entity = response.getEntity();
		InputStream is = entity.getContent();
		//convert response to string
		
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
				     sb.append(line + "\n");
				}
				is.close();
				
				row=sb.toString();
				
				

				 } 
				catch(Exception ex){
					ex.printStackTrace();
				}

				//parse json data
				try{
				JSONArray jArray = new JSONArray(row);
				for(int i=0;i<jArray.length();i++){
				        JSONObject json_data = jArray.getJSONObject(i);
				        idEvent = json_data.getString("id_event");
				        
			    
				        
				}
				
				}catch(JSONException ex){
				Log.e(TAG, "Error parsing data "+ex.toString());
				}
				return idEvent;
	


}
	
	
}	
	
	
			
				
